package com.daoshu.socket.server;

import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.daoshu.socket.config.WebsocketConfig;
import com.daoshu.socket.service.impl.UserAuthorizationListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * @ClassName: SocketIoServer
 * @description:
 * @author: Allen
 * @create: 2019-06-24 15:36
 **/
@Component
@Order(value = 1)
@Slf4j
public class SocketIoServer implements CommandLineRunner {


    @Autowired
    WebsocketConfig websocketConfig;

    private SocketIOServer server;

    @Bean
    public SocketIOServer webSocketServer() {
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setPort(websocketConfig.getPort());
        // 协议升级超时时间（毫秒），默认10000。HTTP握手升级为ws协议超时时间
        config.setUpgradeTimeout(websocketConfig.getUpgradeTimeout());
        // Ping消息间隔（毫秒），默认25000。客户端向服务器发送一条心跳消息间隔
        config.setPingInterval(websocketConfig.getPingInterval());
        // Ping消息超时时间（毫秒），默认60000，这个时间间隔内没有接收到心跳消息就会发送超时事件
        config.setPingTimeout(websocketConfig.getPingTimeout());
        // 这个版本0.9.0不能处理好namespace和query参数的问题。所以为了做认证必须使用全局默认命名空间
        config.setAuthorizationListener(new UserAuthorizationListener());
        server = new SocketIOServer(config);
        return server;
    }


    @PreDestroy
    public void stop() {
        log.info("stop server");
        server.stop();
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("starting server");
        server.start();
    }


    @Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
        return new SpringAnnotationScanner(socketServer);
    }

}
